from django.db import models
from django.contrib.auth.models import User
from django_ckeditor_5.fields import CKEditor5Field


class StoryCategory(models.Model):
    """故事分类模型"""
    name = models.CharField(max_length=50, verbose_name='分类名称')
    description = models.TextField(blank=True, null=True, verbose_name='分类描述')
    order = models.IntegerField(default=0, verbose_name='排序')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        ordering = ['order', 'created_at']
        verbose_name = '故事分类'
        verbose_name_plural = '故事分类'
        
    def __str__(self):
        return self.name
        
    def story_count(self):
        """返回该分类下的故事数量"""
        return self.stories.count()
    story_count.short_description = '故事数量'


class Story(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='stories', verbose_name='作者')
    title = models.CharField(max_length=200, verbose_name='标题')
    content = CKEditor5Field(config_name='extends', verbose_name='内容')
    category = models.ForeignKey(StoryCategory, on_delete=models.SET_NULL, null=True, blank=True, 
                               related_name='stories', verbose_name='分类')
    keywords = models.CharField(max_length=200, blank=True, verbose_name='关键词')
    views = models.PositiveIntegerField(default=0, verbose_name='浏览量')
    likes = models.PositiveIntegerField(default=0, verbose_name='点赞数')
    is_draft = models.BooleanField(default=False, verbose_name='是否为草稿')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        ordering = ['-created_at']
        verbose_name = '故事'
        verbose_name_plural = '故事'

    def __str__(self):
        return self.title

    def get_likes_count(self):
        """返回实际的点赞数量"""
        from interactive.models import Like
        return Like.objects.filter(story=self).count()
        
    def update_likes_count(self):
        """更新点赞数量字段"""
        from interactive.models import Like
        actual_count = Like.objects.filter(story=self).count()
        if self.likes != actual_count:
            self.likes = actual_count
            self.save(update_fields=['likes'])
        return self.likes
        
    def get_category_display(self):
        """获取分类显示名称"""
        if self.category:
            return self.category.name
        return '未分类'